<?php
    //远程获取内容函数
	function get_url_contents($url,$istrue=0)
	{
		if(function_exists('curl_init')){
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
				$result =  curl_exec($ch);
				curl_close($ch);
		}else{
				$result = file_get_contents($url);
		}
		if(!$istrue){
			return json_decode($result,true);
		}else{
			return $result;
		}
	}

	function sWritePlCache()
	{
		global $short_name,$secret,$limit;
		if(!$short_name || !$secret){
			exit('参数未配置正确！');
		}
		if(!$limit) $limit=50;
		$url = 'http://api.duoshuo.com/log/list.json?short_name='.$short_name.'&secret='.$secret.'&limit='.$limit.'&order=desc';
		//获取评论列表
		$result2 = get_url_contents($url,1);
		$result = json_decode($result2,true);
		if($result)
		{
			$plArr='';
			$key=0;
			foreach($result['response'] as $k=>$v)
			{
				$thread_key = $v['meta']['thread_key'];
				if(!$thread_key) continue;
				if($v['action']!='create') continue;

				//获取单条文章评论信息
				$inforurl = 'http://api.duoshuo.com/threads/listPosts.json?order=desc&thread_key='.$thread_key.'&short_name='.$short_name.'&page=1&limit=1';
				$infopl = get_url_contents($inforurl);

				$plArr[$key]=array(
						'title'=>$infopl['thread']['title'], //标题
						'titleurl'=>$infopl['thread']['url'], //链接地址
						'likes'=>$infopl['thread']['likes'], //喜欢数
						'dislikes'=>$infopl['thread']['dislikes'], //不喜欢数
						'comments'=>$infopl['thread']['comments'], //评论数
						'saytext'=>$v['meta']['message'],
						'saytime'=>$v['date'],
				);

				//获取用户信息
				$user_id = $v['user_id'];
				if($user_id) {
					$userUrl = 'http://api.duoshuo.com/users/profile.json?user_id='.$user_id;
					$userinfo = get_url_contents($userUrl);
					$userinfo = $userinfo['response'];
					$plArr[$key]['username']=$userinfo['name'];
					$userpic = $userinfo['avatar_url'] ? $userinfo['avatar_url'] : $userinfo['connected_services']['qqt']['avatar_url'];
					if(!$userpic){
						$userpic = $userinfo['connected_services']['qzone']['avatar_url'];
						if(!$userpic){
							$userpic='/skin/shu/images/nopic.jpg';
						}
					}

					$plArr[$key]['userpic']=$userpic;
				}else{
					$plArr[$key]['username']='网友';
					$plArr[$key]['userpic']='/skin/shu/images/nopic.jpg';
				}
				$key++;
			}
		}

		$pldata = serialize($plArr);
		$plstr = "<?php \n";
		$plstr .="\$pldata='$pldata';\n";
		$plstr .="?>";
		file_put_contents('pldata.php',$plstr);
		return $result2;
	}

	//配置信息
	$short_name='wjsyxx'; //短域名
	$secret = '20fbe31e5497610af187047981a0522b'; //密钥
	$limit = 50;
	//开始调用
	$enews = $_GET['enews'];
	if($enews=='updatedsinfo'){
		$reurl = $_SERVER['HTTP_REFERER'];
		sWritePlCache();
		echo '<a href="'.$reurl.'">更新评论完毕！点击返回！</a>';
	}else{
		echo sWritePlCache();
	}

?>